<template>
  <div>
    <div class="header-btn">
      <div>{{ id ? '编辑' : '创建' }}标签基础信息与标签规则</div>
      <div>
        <el-button type="primary" :loading="loading" @click="ok">确认</el-button>
        <el-button type="info" plain @click="goBack">返回</el-button>
      </div>
    </div>
    <div class="wrap g-card" style="margin-bottom: 20px">
      <div class="title-header">基础信息</div>
      <el-row>
        <el-col :xs="24" :sm="22" :md="20" :lg="18" :xl="16">
          <el-form label-width="120px" label-position="right">
            <el-form-item label="标签名称" required>
              <el-input v-model="tagName" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="标签分组" required>
              <!-- <el-select v-model="tagGroup" value-key="tagGroupId" style="width: 100%;">
                <el-option-group v-for="item in mainList" :key="item.id" :label="item.groupName">
                  <el-option v-for="i in item.tagGroupList" :key="i.id" :label="i.groupName" :value="{tagGroupId: i.id, tagGroupName: i.groupName}"></el-option>
                </el-option-group>
              </el-select> -->
              <el-select v-model="tagGroup" value-key="tagGroupId" style="width: 100%;">
                <el-option v-for="item in  mainList" :key="item.groupId"
                  :value="{ tagGroupId: item.groupId, tagGroupName: item.groupName }" :label="item.groupName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="标签说明">
              <el-input v-model="tagInfo" type="textarea" placeholder="请输入"></el-input>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <div v-if="tagType == 0" class="wrap g-card" style="margin-bottom: 20px">
      <div class="title-header">标签规则</div>
      <div class="container">
        <p class="con-title">创建规则</p>
        <p class="con-notice">在全部用户中，将满足以下条件的用户分为 1 个分层，系统会按照以下自定义分层的顺序进行用户匹配！</p>
        <div class="con-level">
          <div v-for="(item, index) in levels" :key="index" @click="levelTap(index)"
            :class="`level item ${index === levelActived ? 'actived' : ''}`">
            <span>{{ item.name }}</span>
            <el-dropdown trigger="click">
              <i class="el-icon-more" @click.stop></i>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="itemEdit(index)">复制</el-dropdown-item>
                <el-dropdown-item :disabled="levels.length === 1" @click.native="itemDel(index)">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div class="level add" @click="addLevel">
            <span><i class="el-icon-plus"></i></span>
            <span>分层</span>
          </div>
        </div>
        <el-row>
          <el-col :xs="24" :sm="22" :md="20" :lg="18" :xl="16">
            <el-input class="level-ipt" placeholder="请输入" v-model="levels[levelActived].name"></el-input>
            <el-input class="level-ipt" type="textarea" placeholder="请输入分层描述"
              v-model="levels[levelActived].content"></el-input>
            <div class="con-list">
              <div class="relation"><span class="and" @click="relationTap">{{ levels[levelActived].relation == 'true' ?
                '且' : '或'
              }}</span></div>
              <div class="tag-con">
                <div class="tag-item">
                  <p class="tag-item-header">客户属性满足<span class="add" @click="addAttribute"><i
                        class="el-icon-circle-plus"></i>&nbsp;添加</span></p>
                  <div class="tag-first" v-if="levels[levelActived].attributes.children.length">
                    <div class="relation" v-if="levels[levelActived].attributes.children.length > 1"><span class="and"
                        @click="tagFirstRelationTap(levels[levelActived].attributes.relation)">{{
                          levels[levelActived].attributes.relation == 'true' ? '且' : '或' }}</span></div>
                    <div class="tag-first-con">
                      <div class="tag-second" v-for="(item, index) in levels[levelActived].attributes.children"
                        :key="index">
                        <div class="relation" v-if="item.children.length > 1"><span class="and"
                            @click="tagSecondRelationTap(index, item.relation)">{{ item.relation == 'true' ? '且' : '或'
                            }}</span>
                        </div>
                        <div class="tags">
                          <div class="item" v-for="(itm, idx) in item.children" :key="idx">
                            <div>
                              <el-select v-model="itm.value" style="width: 150px">
                                <el-option v-for="item in attributesOptions" :key="item.attributeName"
                                  :label="item.attributeShowName" :value="item.attributeName">
                                </el-option>
                              </el-select>
                              <el-select v-model="itm.flag" style="width: 100px" ref="attrSecondSelect">
                                <el-option v-for="item in attributesSuboptions[itm.value]" :key="item.value"
                                  :label="item.label" :value="item.value" />
                              </el-select>
                              <el-input v-show="attrShowStart[itm.value] && noshowValueSelected.indexOf(itm.flag) == -1"
                                v-model="itm.cont" style="width: 150px"></el-input>
                              <el-select v-show="!attrShowStart[itm.value] && noshowValueSelected.indexOf(itm.flag) == -1"
                                v-model="itm.cont" :clearable="true" style="width: 150px">
                                <el-option v-for="item in attributesChildrenOptions[itm.value]" :key="item" :label="item"
                                  :value="item" />
                              </el-select>
                            </div>
                            <div class="opt">
                              <span class="add" @click="addSecondAttribute(index, idx)"
                                v-if="item.children.length - 1 === idx"><i
                                  class="el-icon-circle-plus-outline"></i>&nbsp;新增</span>
                              &nbsp;&nbsp;&nbsp;&nbsp;
                              <span class="del" @click="delAttribute(index, idx)"><i
                                  class="el-icon-close icon-hover"></i></span>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="tag-item">
                  <p class="tag-item-header">客户行为满足<span class="add" @click="addBehavior"><i
                        class="el-icon-circle-plus"></i>&nbsp;添加</span></p>
                  <div class="tag-first" v-if="levels[levelActived].cusBehaviors.children.length">
                    <div class="relation" v-if="levels[levelActived].cusBehaviors.children.length > 1"><span class="and"
                        @click="tagFirstRelationBehaviorTap(levels[levelActived].cusBehaviors.relation)">{{
                          levels[levelActived].cusBehaviors.relation == 'true' ? '且' : '或' }}</span></div>
                    <div class="tag-first-con">
                      <div class="tag-second" v-for="(item, index) in levels[levelActived].cusBehaviors.children"
                        :key="index">
                        <div class="relation" v-if="item.children.length > 1"><span class="and"
                            @click="tagSecondRelationBehaviorTap(index, item.relation)">{{ item.relation == 'true' ? '且' :
                              '或'
                            }}</span></div>
                        <div class="tags">
                          <div class="item behavior" v-for="(itm, idx) in item.children" :key="idx">
                            <div class="behavior-item-top">
                              <div>
                                <el-date-picker v-model="itm.timelist" value-format="yyyy-MM-dd" type="daterange"
                                  range-separator="至" :editable="false" :clearable="false"></el-date-picker>
                                <el-select style="width: 80px;" v-model="itm.make">
                                  <el-option value="0" label="做过">做过</el-option>
                                  <el-option value="1" label="未做过"></el-option>
                                </el-select>
                                <el-select v-model="itm.cont" style="width: 170px">
                                  <el-option v-for="item in behaviorsOptions" :key="item.attributeShowName"
                                    :label="item.attributeShowName" :value="item.attributeShowName">{{
                                      item.attributeShowName }}
                                  </el-option>
                                </el-select>
                                <span class="filter-btn" @click="addThirdBehavior(index, idx)"><i
                                    class="el-icon-plus"></i>添加筛选</span>
                              </div>
                              <div class="opt">
                                <span class="add" @click="addSecondBehavior(index, idx)"
                                  v-if="item.children.length - 1 === idx"><i
                                    class="el-icon-circle-plus-outline"></i>&nbsp;新增</span>
                                &nbsp;&nbsp;&nbsp;&nbsp;
                                <span class="del" @click="delBehavior(index, idx)"><i
                                    class="el-icon-close icon-hover"></i></span>
                              </div>
                            </div>
                            <div class="behavior-item-center" v-if="itm.children.length">
                              <div class="behavior-item-center-left">
                                <span>且满足</span>
                              </div>
                              <div class="behavior-item-center-center" v-if="itm.children.length > 1">
                                <span class="line top"></span>
                                <span class="and" @click="tagThirdRelationBehaviorTap(index, idx, itm.relation)">{{
                                  itm.relation == 'true' ? '且' : '或' }}</span>
                                <span class="line bottom"></span>
                              </div>
                              <div class="behavior-item-center-right">
                                <div class="behavior-item-center-right-con" v-for="(m, i) in itm.children" :key="i">
                                  <el-select v-model="m.cont" style="width: 170px">
                                    <el-option v-for="item in behaviorsOptions" :key="item.attributeShowName"
                                      :label="item.attributeShowName" :value="item.attributeShowName"></el-option>
                                  </el-select>
                                  <el-select v-model="m.flag" style="width: 100px">
                                    <el-option label="做过" value="0"></el-option>
                                    <el-option label="没做过" value="1"></el-option>
                                  </el-select>
                                  <el-input style="width: 100px;" v-model="m.value" placeholder="次数"></el-input>
                                  <span class="del" @click="delThirdBehavior(index, idx, i)"><i
                                      class="el-icon-close icon-hover"></i></span>
                                </div>
                              </div>
                            </div>
                            <div class="behavior-item-bottom">
                              <el-cascader v-model="itm.times" :options="behaviorsSubOptions[itm.cont]"
                                @change="val => cascaderChange(val, behaviorsSubOptions[itm.cont], itm)"
                                style="width:170px"></el-cascader>
                              <el-select v-model="itm.flag" style="width: 100px ; margin-left: 12px">
                                <el-option v-for="item in sortList" :key="item.value" :label="item.value"
                                  :value="item.value"></el-option>
                              </el-select>
                              <el-input v-if="(itm.flag !== '区间' && itm.flag !== 'TOPN')" v-model="itm.value"
                                placeholder="次数" style="width: 100px ;"></el-input>
                              <span v-if="(itm.flag !== '区间' && itm.flag !== 'TOPN')">&nbsp;{{ itm.text || '次' }}</span>
                              <el-input v-if="(itm.flag === '区间')" v-model="itm.value" placeholder="次数"
                                style="width: 100px ;"></el-input>
                              <span v-if="(itm.flag === '区间')">&nbsp;至</span>
                              <el-input v-if="(itm.flag === '区间')" v-model="itm.valuenext
                                " placeholder="次数" style="width: 100px ;"></el-input>
                              <span v-if="(itm.flag === '区间')">&nbsp;{{ itm.text || '次' }}</span>
                              <el-select v-if="(itm.flag === 'TOPN')" v-model="itm.topflag"
                                style="width: 100px ; margin-left: 12px">
                                <el-option v-for="item in topFlagList" :key="item.value" :label="item.label"
                                  :value="item.value"></el-option>
                              </el-select>
                              <el-input v-if="(itm.flag === 'TOPN')" v-model="itm.value" placeholder=""
                                style="width: 100px ;"></el-input>
                              <span v-if="(itm.flag === 'TOPN' && itm.topflag !== '3')">&nbsp;名</span>
                              <span v-if="(itm.flag === 'TOPN' && itm.topflag === '3')">&nbsp;至</span>
                              <el-input v-if="(itm.flag === 'TOPN' && itm.topflag === '3')" v-model="itm.valuenext
                                " placeholder="" style="width: 100px ;"></el-input>
                              <span v-if="(itm.flag === 'TOPN' && itm.topflag === '3')">&nbsp;名</span>

                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="tag-item">
                  <p class="tag-item-header">客户行为序列<span class="add" @click="addSequence"><i
                        class="el-icon-circle-plus"></i>&nbsp;添加</span></p>
                  <div class="tag-first" v-if="levels[levelActived].cusBehaviorSeqs.children.length">
                    <div class="relation" v-if="levels[levelActived].cusBehaviorSeqs.children.length > 1"><span
                        class="and" @click="tagFirstRelationSequenceTap(levels[levelActived].cusBehaviorSeqs.relation)">{{
                          levels[levelActived].cusBehaviorSeqs.relation == 'true' ? '且' : '或' }}</span></div>
                    <div class="tag-first-con">
                      <div class="tag-second" v-for="(item, index) in levels[levelActived].cusBehaviorSeqs.children"
                        :key="index">
                        <div class="tags">
                          <div class="item sequence">
                            <div class="sequence-top">
                              <div class="sequence-main">
                                <span class="letter">{{ alphabet[index] }}</span>
                                <el-date-picker v-model="item.timelist" value-format="yyyy-MM-dd" type="daterange"
                                  range-separator="至" :editable="false" :clearable="false"></el-date-picker>&nbsp;
                                <span style="font-size: 12px; color: #999;">依次做过</span>
                              </div>
                              <div class="opt">
                                <span class="add" @click="addSecondSequence(index)"><i
                                    class="el-icon-circle-plus-outline"></i>&nbsp;添加事件</span>
                                &nbsp;&nbsp;&nbsp;&nbsp;
                                <span class="del" @click="delSequence(index)"><i
                                    class="el-icon-close icon-hover"></i></span>
                              </div>
                            </div>
                            <div class="item behavior" v-for="(itm, idx) in item.children" :key="idx">
                              <div class="behavior-item-top sequence">
                                <div style="flex-grow: 1;">
                                  <div class="letter">{{ alphabet[index] + (idx + 1) }}</div>
                                  <el-select style="width: 170px;" v-model="itm.cusBehavior"
                                    @change="sequenceChange(index, idx, $event)">
                                    <el-option v-for="item in behaviorsOptions" :key="item.attributeShowName"
                                      :label="item.attributeShowName" :value="item.attributeShowName">{{
                                        item.attributeShowName }}
                                    </el-option>
                                  </el-select>
                                  <span class="filter-btn" @click="addThirdSequence(index, idx)" v-if="false"><i
                                      class="el-icon-plus"></i>添加筛选</span>
                                </div>
                                <span class="del" @click="delSecondSequence(index, idx)" v-if="idx > 1"><i
                                    class="el-icon-close icon-hover"></i></span>
                              </div>
                              <div class="behavior-item-center" v-if="itm.children.length">
                                <div class="behavior-item-center-left">
                                  <span>且满足</span>
                                </div>
                                <div class="behavior-item-center-center" v-if="itm.children.length > 1">
                                  <span class="line top"></span>
                                  <span class="and" @click="tagSecondSequenceRelationTap(index, idx, itm.relation)">{{
                                    itm.relation == 'true' ? '且' : '或' }}</span>
                                  <span class="line bottom"></span>
                                </div>
                                <div class="behavior-item-center-right">
                                  <div class="behavior-item-center-right-con" v-for="(m, i) in itm.children" :key="i">
                                    <el-select style="width: 150px;" v-model="m.additionalAttribute">
                                      <el-option v-for="v in itm.values" :key="v.tagValue" :value="v.tagValue"
                                        :label="v.tagKey"></el-option>
                                    </el-select>
                                    <el-select style="width: 100px;" v-model="m.operator">
                                      <el-option v-for="o in operators" :key="o.tagValue" :value="o.tagValue"
                                        :label="o.tagKey"></el-option>
                                    </el-select>
                                    <el-input style="width: 100px;" v-model="m.value" placeholder="请输入"></el-input>
                                    <span class="del" @click="delThirdSequence(index, idx, i)"><i
                                        class="el-icon-close icon-hover"></i></span>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
        <p class="con-title">更新方式</p>
        <div>
          <el-radio-group v-model="params.ways">
            <el-radio-button label="1">例行</el-radio-button>
            <el-radio-button label="2">手动</el-radio-button>
          </el-radio-group>
        </div>
        <div class="ways-con" v-if="params.ways === '1'">
          <span style="padding: 0 5px;color: #333;">按</span>
          <el-select v-model="params.calc" style="width: 80px;">
            <el-option value="day" label="天"></el-option>
            <el-option value="week" label="周"></el-option>
            <el-option value="month" label="月"></el-option>
          </el-select>
          <span style="padding: 0 5px;color: #333;">计算</span>
          <span v-if="params.calc === 'day'" style="font-size: 12px;color: #999;">标签每日凌晨更新！</span>
          <span v-if="params.calc === 'week'" style="font-size: 12px;color: #999;">标签每周一凌晨更新！</span>
          <span v-if="params.calc === 'month'" style="font-size: 12px;color: #999;">标签每月一号凌晨更新！</span>
        </div>
        <div class="ways-con" v-if="params.ways === '2'">
          <span style="font-size: 12px;color: #999;">标签生成后，通过手动点击“生成”按钮，进行数据的更新！</span>
        </div>
      </div>
    </div>
    <behaviorDistribution v-else :levels="levels" :behaviorsOptions="behaviorsOptions"
      :behaviorsSubOptions="behaviorsSubOptions" :sortList="sortList" :addThirdBehavior="addThirdBehavior"
      :delThirdBehavior="delThirdBehavior" :tagThirdRelationBehaviorTap="tagThirdRelationBehaviorTap" :tagType="tagType"
      :params="params" :topFlagList="topFlagList" :tagMap="tagMap" :cascaderChange="cascaderChange" />
    <!-- <div v-else-if="tagType == 3"></div> -->
  </div>
</template>

<script>
import { groupList, tagList, createTag, updateTag, tagInfo } from '@/api/customer/label'
import { queryBasicTagInfo, queryTagInfo, getProvinceList, getCityList, getRiskList } from '@/api/swarm'
import behaviorDistribution from './components/behaviorDistribution'

export default {
  components: { behaviorDistribution },
  data() {
    return {
      text: '',
      tagMap: {
        0: { text: '基础属性', byte: 'cusBehaviors' },
        3: { text: '行为分布结果', byte: 'behaviorDistributions' },
        1: { text: '首末次特征', byte: 'behaviorFirstLasts' },
        2: { text: '事件偏好属性', byte: 'behaviorPreferences' },
      },
      loading: false,
      id: '',
      tagName: '',
      tagGroup: null,
      tagType: '',
      mainList: [],
      tagGroupId: '',
      tagGroupName: '',
      tagInfo: '',
      v: [],
      params: {
        ways: '1',
        calc: 'day',
      },
      alphabet: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
      behavior: [],
      levelActived: 0,
      operators: [],
      attributeValues: [],
      behaviorTopChoose: [],
      behaviorBottomChoose: [],
      levels: [
        {
          name: '分层',
          content: '',
          relation: true,
          attributes: {
            relation: true,
            children: [],
          },
          cusBehaviors: {
            relation: true,
            children: [],
          },
          cusBehaviorSeqs: {
            relation: true,
            children: [],
          },

          behaviorDistributions: {
            relation: true,
            children: [],
          },
          behaviorFirstLasts: {
            relation: true,
            children: [],
          },
          behaviorPreferences: {
            relation: true,
            children: [],
          },
        }
      ],
      attributesOptions: [],
      attributesSuboptions: {},
      attributesChildrenOptions: {},
      behaviorsOptions: [],
      behaviorsSubOptions: [],
      sortList: [
        { flag: '大于等于', value: '≥' },
        { flag: '大于', value: '>' },
        { flag: '小于等于', value: '≤' },
        { flag: '小于', value: '<' },
        { flag: '不等于', value: '≠' },
        { flag: '等于', value: '=' },
        { flag: '区间', value: '区间' },
        // { flag: 'TOPN', value: 'TOPN' }
      ],
      //满足值不展示输入框的值
      noshowValueSelected: ['5', '6', '7', '8'],
      topFlagList: [
        { value: '1', label: '前' },
        { value: '2', label: '后' },
        { value: '3', label: '区间' }
      ],
      //客户属性满足控制后续输入框和下拉框展示
      attrShowStart: {},
      attrShowInput: {},
      attrShowSelect: {},
      attrSpelist: ['province', 'city', 'preference_insured_products', 'browse_product_preferences'],
      provinceList: [],
      cityList: [],
      riskList: [],
      rules: {
        behaviorFirstLasts: ['timelist', 'cont', 'occurrence', 'pointTime',],
        behaviorDistributions: ['timelist', 'cont', 'distributeType',], // 'date',
        behaviorPreferences: ['timelist', 'cont', 'urlState', 'urlStateMost', 'mostValue',],

        attributes: { text: '客户属性满足', byte: ['value', 'flag',] }, // flag 'cont', 5 6 7 8
        cusBehaviors: { text: '客户行为满足', byte: ['value', 'make', 'cont', 'times', 'flag'] }, // valuenext timelist
        cusBehaviorSeqs: { text: '客户行为序列', byte: ['cusBehavior',] }, // timelist
      }
    }
  },
  created() {
    this.init();
    this.getPCRList();
    this.$nextTick(() => {
      this.queryTagInfo();
    })
  },
  methods: {
    init() {
      this.getGroupList()
      // this.getAttributeTags()
      // this.getBehaviorTags()
      // this.getSequenceTags()
      // this.getOperator()

      // this.getInfo()
      if (this.$route.query.hasOwnProperty('tagType')) {
        this.tagType = this.$route.query.tagType
        if (this.tagType > 0) {
          this.levels[0].name = ''
          this.$set(this.levels[this.levelActived][this.tagMap[this.tagType].byte], 'children',
            // {
            //   children:
            [{
              relation: true,
              children:
                [
                  {
                    timelist: [],
                    cont: '',
                    make: '0',
                    relation: true,
                    children: [],
                  }
                ],
            }]
            // }
          )
        }
      }
      if (this.$route.query.hasOwnProperty('id')) {
        this.id = this.$route.query.id
        this.getInfo(this.$route.query.id)
      }
    },
    createdInfoC() {
      if (this.id && this.tagInfo && Object.keys(this.behaviorsSubOptions).length) {
        if (this.tagType > 0) {
          let children = this.levels[this.levelActived][this.tagMap[this.tagType].byte].children
          children.forEach(child => {
            child.children.forEach(itm => {
              itm.children.length && itm.children.forEach(m => {
                console.log(m.times, this.behaviorsSubOptions[itm.cont], m);
                this.cascaderChange(m.times, this.behaviorsSubOptions[itm.cont], m)
              })
            })
          })
        }
      }
    },
    getInfo(id) {
      tagInfo({ id }).then(res => {
        if (res.code === 200) {
          const { data } = res
          this.tagName = data.tagName
          this.tagType = data.tagType
          this.tagGroup = {
            tagGroupName: data.tagGroupName,
            tagGroupId: data.tagGroupId
          }
          this.tagInfo = data.tagInfo
          this.params.ways = data.updateType
          this.params.calc = data.updateJob
          this.levels = data.allLayerDTOList?.map(item => {
            return {
              ...item,
              name: item.tagLayName,
              content: item.tagLayDescribe,
            }
          })
          this.createdInfoC()
        }
      })
    },
    getGroupList() {
      groupList().then(res => {
        if (res.code === 200) {
          const { rows } = res
          this.mainList = rows
        } else {
          this.mainList = []
        }
      })
    },
    queryTagInfo() {
      queryBasicTagInfo({ code: 1 }).then((res) => {
        this.attributesOptions = res.data.attributeInfoList
        this.attributesOptions.forEach((item) => {
          if (item.tagFlagList) {
            this.attributesSuboptions[item.attributeName] = item.tagFlagList[0].tagInfolist || [];
            if (this.attrSpelist.indexOf(item.attributeName == -1)) {
              this.attributesChildrenOptions[item.attributeName] = item.tagFlagList[0].enums || [];
            } else if (item.attributeName == 'province') {
              let newArr = this.provinceList.map(item => {
                return item.label;
              })
              this.attributesChildrenOptions[item.attributeName] = newArr || [];
            } else if (item.attributeName == 'city') {
              let newArr = this.cityList.map(item => {
                return item.label;
              })
              this.attributesChildrenOptions[item.attributeName] = newArr || [];
            } else if (item.attributeName == 'preference_insured_products' || item.attributeName == 'browse_product_preferences') {
              let newArr = this.riskList.map(item => {
                return item.label;
              })
              this.attributesChildrenOptions[item.attributeName] = newArr || [];
            }
            if (this.attributesChildrenOptions[item.attributeName].length == 0) {
              this.attrShowStart[item.attributeName] = true;
            } else if (this.attributesChildrenOptions[item.attributeName].length > 0) {
              this.attrShowStart[item.attributeName] = false;
            }
          }
        })
      })
      queryTagInfo({ code: 2 }).then((res) => {
        this.behaviorsOptions = res.data.attributeInfoList
        this.behaviorsOptions.forEach((item) => {
          this.behaviorsSubOptions[item.attributeShowName] =
            item.tagFlagList || []
        })
        this.createdInfoC()
        // console.log(this.behaviorsSubOptions, Object.keys(this.behaviorsSubOptions) )
      })
    },
    goBack() {
      this.$router.back()
    },
    itemEdit(index) {
      const obj = JSON.parse(JSON.stringify(this.levels[index]))
      this.levels.splice(index, 0, obj)
      this.levelActived = index + 1
    },
    itemDel(index) {
      if (this.levelActived === (this.levels.length - 1)) {
        this.levelActived = this.levelActived - 1
      }
      this.levels.splice(index, 1)
    },
    addLevel() {
      if (this.levels.length > 23) {
        this.$message.error('最多支持创建24个分层');
        return
      }
      this.levels.push({
        name: '分层' + (this.levels.length + 1),
        content: '',
        attributes: {
          relation: true,
          children: [],
        },
        cusBehaviors: {
          relation: true,
          children: [],
        },
        cusBehaviorSeqs: {
          relation: true,
          children: [],
        },

        behaviorDistributions: {
          relation: true,
          children: [],
        },
        behaviorFirstLasts: {
          relation: true,
          children: [],
        },
        behaviorPreferences: {
          relation: true,
          children: [],
        },
      })
      this.levelActived = this.levels.length - 1
    },
    levelTap(index) {
      this.levelActived = index
    },
    addAttribute() {
      this.levels[this.levelActived].attributes.children.push({
        relation: true,
        children: [
          {
            value: '',
            flag: '',
            cont: '',
          }
        ],
      })
    },
    addBehavior() {
      this.levels[this.levelActived].cusBehaviors.children.push({
        relation: true,
        children: [
          {
            value: '',
            timelist: [],
            make: '',
            cont: '',
            times: '',
            flag: '',
            relation: true,
            children: [],
          }
        ],
      })
    },
    addSequence() {
      this.levels[this.levelActived].cusBehaviorSeqs.children.push({
        time: [],
        children: [
          {
            value: '',
            cusBehavior: '',
            flag: '',
            relation: true,
            children: []
          },
          {
            value: '',
            cusBehavior: '',
            flag: '',
            relation: true,
            children: []
          },
        ],
      },)
    },
    relationTap() {
      this.levels[this.levelActived].relation = !this.levels[this.levelActived].relation
    },
    tagFirstRelationTap(relation) {
      this.levels[this.levelActived].attributes.relation = !relation
    },
    tagFirstRelationBehaviorTap(relation) {
      this.levels[this.levelActived].cusBehaviors.relation = !relation
    },
    tagFirstRelationSequenceTap(relation) {
      this.levels[this.levelActived].cusBehaviorSeqs.relation = !relation
    },
    tagSecondRelationTap(index, relation) {
      this.levels[this.levelActived].attributes.children[index].relation = !relation
    },
    tagSecondRelationBehaviorTap(index, relation) {
      this.levels[this.levelActived].cusBehaviors.children[index].relation = !relation
    },
    tagThirdRelationBehaviorTap(index, idx, relation) {
      this.levels[this.levelActived][this.tagMap[this.tagType].byte].children[index].children[idx].relation = !relation
    },
    tagSecondSequenceRelationTap(index, idx, relation) {
      this.levels[this.levelActived].cusBehaviorSeqs.children[index].children[idx].relation = !relation
    },
    addSecondAttribute(index, idx) {
      this.levels[this.levelActived].attributes.children[index].children.push({
        key: '',
        flag: '',
        value: '',
        values: []
      })
    },
    addSecondBehavior(index, idx) {
      this.levels[this.levelActived].cusBehaviors.children[index].children.push({
        time: [],
        action: '0',
        behavior: '',
        flag: '',
        value: '',
        relation: true,
        children: [],
        values: [],
      })
    },
    addThirdBehavior(index, idx) {
      this.levels[this.levelActived].cusBehaviors.children[index].children[idx].children.push({
        additionalAttribute: '',
        operator: '',
        value: '',
      })
    },
    addSecondSequence(index) {
      this.levels[this.levelActived].cusBehaviorSeqs.children[index].children.push({
        behavior: '',
        relation: true,
        children: [],
        values: [],
      })
    },
    addThirdSequence(index, idx) {
      this.levels[this.levelActived].cusBehaviorSeqs.children[index].children[idx].children.push({
        additionalAttribute: '',
        operator: '',
        value: ''
      })
    },
    delAttribute(index, idx) {
      if (this.levels[this.levelActived].attributes.children[index].children.length === 1) {
        this.levels[this.levelActived].attributes.children.splice(index, 1)
      } else {
        this.levels[this.levelActived].attributes.children[index].children.splice(idx, 1)
      }
    },
    delBehavior(index, idx) {
      if (this.levels[this.levelActived].cusBehaviors.children[index].children.length === 1) {
        this.levels[this.levelActived].cusBehaviors.children.splice(index, 1)
      } else {
        this.levels[this.levelActived].cusBehaviors.children[index].children.splice(idx, 1)
      }
    },
    delSequence(index) {
      this.levels[this.levelActived].cusBehaviorSeqs.children.splice(index, 1)
    },
    delSecondSequence(index, idx) {
      this.levels[this.levelActived].cusBehaviorSeqs.children[index].children.splice(idx, 1)
    },
    delThirdBehavior(index, idx, i) {
      this.levels[this.levelActived].cusBehaviors.children[index].children[idx].children.splice(i, 1)
    },
    delThirdSequence(index, idx, i) {
      this.levels[this.levelActived].cusBehaviorSeqs.children[index].children[idx].children.splice(i, 1)
    },
    sequenceChange(index, idx, value) {
      // const tagTypeList = Array.from(this.behaviorTopChoose.find(item => item.tagValue === value)?.tagTypeList)
      // this.levels[this.levelActived].cusBehaviorSeqs.children[index].children[idx].children = []
      // this.levels[this.levelActived].cusBehaviorSeqs.children[index].children[idx].values = tagTypeList
    },
    cascaderChange(val, options, itme) {
      val && options.some(opt => opt.value == val[0] && (itme.text = opt.unit || ''))
    },
    ok() {
      // if (false) {
      if (this.tagName.match(/^[ ]*$/)) {
        return this.$message.error('请输入标签名称')
      }
      if (this.tagGroup === null) {
        return this.$message.error('请选择标签分组')
      }
      if (this.tagType == 0 && this.levels.some(item => item.name.match(/^[ ]*$/))) {
        return this.$message.error('请输入分层名称')
      }

      if (this.tagType > 0) {
        // console.log(this.levels[0][this.tagMap[this.tagType].byte].children[0].children[0])
        let obj = this.levels[0][this.tagMap[this.tagType].byte].children[0].children[0],
          flag = this.rules[this.tagMap[this.tagType].byte].every(key => {
            if (key == 'timelist') return !!obj[key][0]
            else return !!obj[key]
          });
        if (this.tagType == 1 && obj.pointTime == 2) flag = !!obj.date

        // console.log('flag', flag);
        if (!flag) return this.$message.error('内容配置有误')
      } else {
        console.log(this.levels, '昊总要请客吃日料')
        for (let i = 0; i < this.levels.length; i++) {
          // attributes 客户属性满足
          // cusBehaviors 客户行为满足
          // cusBehaviorSeqs 客户行为序列
          const level = this.levels[i], fKeys = ['attributes', 'cusBehaviors', 'cusBehaviorSeqs'];
          if (level.attributes.children.length == 0) return this.$message.error(level.name + '客户属性内容配置为空')

          // 分层下都为空校验
          if (fKeys.every(fKey => level[fKey].children.length == 0)) return this.$message.error(level.name + '内容配置有误')

          for (let ki = 0; ki < fKeys.length; ki++) {
            const fKey = fKeys[ki], children = level[fKey].children, rule = this.rules[fKey];
            let flag1 = children.every(child => child.children.every(item => {
              // let flag =
              return rule.byte.every(key => {
                // console.log('child', child);
                if (fKey == 'attributes' && key == 'flag' && item.flag && (item.flag < 5 || item.flag > 8)) return !!item.cont;
                else if (fKey == 'cusBehaviors' && item.timelist.length == 0) return false;
                else if (fKey == 'cusBehaviors' && key == 'flag' && item.flag == '区间') return !!item.valuenext
                else if (fKey == 'cusBehaviorSeqs' && (!child.timelist || child.timelist.length == 0)) return false;
                return !!item[key]
              })
              // console.log('flag', flag);
              // return flag
            }))
            // console.log('flag1', flag1);
            if (!flag1) return this.$message.error(level.name + rule.text + '内容配置有误')
          }

          // fKeys.forEach(fKey => level[fKey])
        }
      }
      // }
      // return
      this.loading = true
      const params = {
        tagName: this.tagName,
        tagType: this.tagType, //0-基础属性；1-行为统计
        tagGroupId: this.tagGroup.tagGroupId,
        tagGroupName: this.tagGroup.tagGroupName,
        tagInfo: this.tagInfo,
        allLayerDTOList: [],
        updateType: this.params.ways,
        //  === '例行' ? '1' : '2', //1-例行；2-手动
        updateJob: this.params.calc, //月-month；周-week；天-day
      }
      params.allLayerDTOList = this.levels.map(item => {
        let obj = {
          tagLayName: item.name,
          tagLayDescribe: item.content,
          tagRelationship: this.t(item.relation),
          attributes: item.attributes,
          cusBehaviors: item.cusBehaviors,
          cusBehaviorSeqs: item.cusBehaviorSeqs,

          behaviorDistributions: item.behaviorDistributions,
          behaviorFirstLasts: item.behaviorFirstLasts,
          behaviorPreferences: item.behaviorPreferences,
        }
        // this.levels[this.levelActived], [this.tagMap[this.tagType].byte]
        // if (this.tagType > 0) obj[this.tagMap[this.tagType].byte] = item[this.tagMap[this.tagType].byte]
        return obj
      })
      // console.log('params', params)
      // return
      if (this.id) {
        updateTag({ mainId: this.id, ...params }).then(res => {
          this.loading = false
          if (res.code === 200) {
            this.$message.success(res.msg)
            this.$router.back()
          }
        })
      } else {
        createTag(params).then(res => {
          this.loading = false
          if (res.code === 200) {
            this.$message.success(res.msg)
            this.$router.back()
          }
        })
      }

    },
    t(t) {
      return t ? 'and' : 'or'
    },

    //客户属性满足第二个值改变判断输入选择框的展示与否
    attrSecondSelectChange(val, index, idx) {
      // let af = this.levels[this.levelActived].attributes.children[index].children[idx].value;
      // if(this.noshowValueSelected.indexOf(val) != -1){
      //   this.attrShowInput[af + index + idx] = false;
      //   this.attrShowSelect[af + index + idx] = false;
      // }else {
      //   if (this.attributesChildrenOptions[af] && this.attributesChildrenOptions[af].length == 0) {
      //     this.attrShowInput[af + index + idx] = true;
      //     this.attrShowSelect[af + index + idx] = false;
      //   } else if (this.attributesChildrenOptions[af] && this.attributesChildrenOptions[af].length > 0) {
      //     this.attrShowInput[af + index + idx] = false;
      //     this.attrShowSelect[af + index + idx] = true;
      //   }
      // }
    },

    //获取省份、城市、险种枚举值
    getPCRList() {
      getProvinceList().then((res) => { if (res.code == 200) this.provinceList = res.data.list }).catch(() => { })
      getCityList().then((res) => { if (res.code == 200) this.cityList = res.data.list }).catch(() => { })
      getRiskList().then((res) => { if (res.code == 200) this.riskList = res.data.list }).catch(() => { })
    },

  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/base.scss";

.icon-hover:hover {
  color: $ownStyle
}


.header-btn {
  @include headerBtn;
}

.wrap {
  @include titleWrap;
}

.container {
  padding: 0px 20px;

  .con-title {
    font-size: 14px;
    line-height: 1.5;
    margin: 10px 0;
  }

  .con-notice {
    font-size: 12px;
    line-height: 1.5;
    color: #999;
  }

  .con-level {
    display: flex;
    flex-wrap: wrap;
    padding-top: 10px;

    .level {
      box-sizing: border-box;
      min-width: 200px;
      height: 30px;
      line-height: 30px;
      border-radius: 1000px;
      padding: 0 20px;
      display: flex;
      justify-content: space-between;
      cursor: pointer;
      margin: 0 10px 10px 0;

      &.item {
        border: 1px solid #bbb;

        &.actived {
          border: 1px solid #082aff;
        }
      }

      &.add {
        display: block;
        text-align: center;
        border: 1px dashed #bbb;
      }

      .el-icon-more {
        cursor: pointer;
      }

      // border: 1px solid #082aff;
    }
  }

  .ways-con {
    margin: 10px 0;
  }

  .level-ipt {
    margin-bottom: 10px;
  }

  .con-list {
    display: flex;
    align-items: stretch;

    .relation {
      flex-shrink: 0;
      position: relative;
      width: 26px;

      .and {
        display: block;
        box-sizing: border-box;
        font-size: 12px;
        width: 18px;
        height: 18px;
        text-align: center;
        line-height: 18px;
        color: #082aff;
        background-color: #FFBAA2;
        border-radius: 4px;
        cursor: pointer;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        z-index: 7;
        user-select: none;
      }

      &::after {
        content: '';
        display: block;
        position: absolute;
        width: 3px;
        height: 100%;
        background-color: #FFBAA2;
        top: 0;
        left: 50%;
        transform: translateX(-50%);
        z-index: 6;
      }
    }

    .tag-con {
      flex-grow: 1;

      .tag-item {
        border: 1px solid #bbb;
        padding: 10px;
        border-radius: 5px;

        .tag-item-header {
          color: #333;

          .add {
            float: right;
            color: #666;
            cursor: pointer;

            .el-icon-circle-plus {
              color: #082aff;
            }
          }

        }

        &:not(:last-child) {
          margin-bottom: 10px;
        }

        .tag-first {
          display: flex;
          align-items: stretch;
          margin-top: 10px;

          .tag-first-con {
            flex-grow: 1;

            .tag-second {
              display: flex;
              align-items: stretch;
              width: 100%;

              &:not(:last-child) {
                margin-bottom: 20px;
              }

              .tags {
                flex-grow: 1;

                .item {
                  width: 100%;
                  display: flex;
                  justify-content: space-between;

                  .letter {
                    display: inline-block;
                    width: 20px;
                    height: 20px;
                    text-align: center;
                    line-height: 20px;
                    background-color: #FFBAA2;
                    color: #082aff;
                    margin-right: 5px;
                    border-radius: 3px;
                  }

                  &.behavior {
                    display: block;

                    .behavior-item-top {
                      width: 100%;
                      display: flex;
                      justify-content: space-between;

                      &.sequence {
                        justify-content: left;
                        align-items: center;

                        .letter {
                          display: inline-block;
                          width: 20px;
                          height: 20px;
                          text-align: center;
                          line-height: 18px;
                          box-sizing: border-box;
                          font-size: 12px;
                          border: 1px solid #eee;
                          background-color: #f2f2f2;
                          color: #999;
                          border-radius: 3px;
                        }

                        .del {
                          cursor: pointer;
                          color: #999;

                          &:hover {
                            color: #082aff;
                          }
                        }
                      }
                    }

                    .behavior-item-center {
                      display: flex;
                      align-items: stretch;
                      margin-top: 10px;
                      justify-items: center;

                      .behavior-item-center-left {
                        width: 70px;
                        font-size: 12px;
                        color: #082aff;
                        border-right: 2px solid #FFBAA2;
                        text-align: center;
                        line-height: 30px;
                      }

                      .behavior-item-center-center {
                        display: flex;
                        flex-direction: column;
                        width: 40px;
                        align-items: center;
                        justify-content: center;
                        padding: 14px 0;

                        .and {
                          display: block;
                          flex-shrink: 0;
                          width: 22px;
                          height: 22px;
                          color: #999;
                          border: 1px solid #eee;
                          border-radius: 3px;
                          text-align: center;
                          line-height: 20px;
                          font-size: 12px;
                          cursor: pointer;
                          user-select: none;

                          &:hover {
                            color: #FFBAA2;
                            border: 1px solid #FFBAA2;
                          }
                        }

                        .line {
                          display: block;
                          flex-grow: 0.5;
                          // background-color: red;
                          width: 50%;
                          transform: translateX(50%);
                          border-left: 1px solid #FFBAA2;

                          &.top {
                            border-top: 1px solid #FFBAA2;
                            border-top-left-radius: 2px;
                          }

                          &.bottom {
                            border-bottom: 1px solid #FFBAA2;
                            border-bottom-left-radius: 2px;
                          }
                        }
                      }

                      .behavior-item-center-right {
                        .behavior-item-center-right-con {
                          .del {
                            margin-left: 5px;
                            color: #999;
                            cursor: pointer;

                            &:hover {
                              color: #082aff;
                            }
                          }

                          &:not(:last-child) {
                            margin-bottom: 5px;
                          }
                        }
                      }
                    }

                    .behavior-item-bottom {
                      margin-top: 10px;
                    }
                  }

                  &.sequence {
                    flex-wrap: wrap;

                    .sequence-top {
                      width: 100%;
                      display: flex;
                      margin-bottom: 10px;

                      .sequence-main {
                        flex-grow: 1;
                      }
                    }
                  }

                  .el-select {
                    margin-right: 10px;
                  }

                  .filter-btn {
                    font-size: 12px;
                    color: #999;
                    cursor: pointer;

                    &:hover {
                      color: #082aff;
                    }
                  }

                  .opt {
                    display: inline-block;
                    color: #999;
                    line-height: 32px;
                    flex-shrink: 0;

                    .add {
                      cursor: pointer;

                      .el-icon-circle-plus-outline {
                        color: #082aff;
                      }
                    }

                    .del {
                      cursor: pointer;

                      &:hover {
                        color: #082aff;
                      }
                    }

                  }

                  &:not(:last-child) {
                    margin-bottom: 10px;
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  ::v-deep {
    .el-date-editor {
      width: 186px;
      padding: 3px 0 3px 6px;
      margin-right: 10px;

      .el-icon-date {
        width: 20px;
        flex-shrink: 0;
      }

      .el-range-input {
        flex-shrink: 0;
      }

      .el-range-separator {
        width: 16px;
        text-align: center;
        font-size: 12px;
        padding: 0;
        flex-shrink: 0;
      }

      .el-range__close-icon {
        display: none;
      }
    }
  }
}
</style>
